package com.ohuang.jiaxiaotong.Activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.Ohuang.ilivedata.MyLiveData;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.myhttp.CallBackObject;
import com.example.myhttp.CallBackString;
import com.example.myhttp.Ihttp;
import com.ohuang.jiaxiaotong.MainActivity;
import com.ohuang.jiaxiaotong.MyHttpURL;
import com.ohuang.jiaxiaotong.R;
import com.ohuang.jiaxiaotong.Util.Ohuang;
import com.ohuang.jiaxiaotong.Util.Sys;
import com.ohuang.jiaxiaotong.base.BaseAc;
import com.ohuang.jiaxiaotong.entity.User;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.HashMap;

public class LoginActivity extends BaseAc {
    private ImageView imageView;
    private EditText editText_name, editText_psd;
    private String username, password;
    private static final int SI_SUCCESS = 0, SI_FAIL = 1, SI_ERROR = 2, SI_OTHER = 3;
    private Dialog dialogLoading;
    private String TAG="LoginActivity";
    private MyHandler mHandler=new MyHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setTitle("登录");
        Ohuang.changeStatusBarTextImgColor(this, true);
        initview();

    }

    private void initview() {


        imageView = findViewById(R.id.img_icon_login);
        editText_name = findViewById(R.id.edit_username_login);
        editText_psd = (EditText) findViewById(R.id.edit_psd_login);
        editText_name.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mHandler.hasMessages(1)) {//信息搜索
                    mHandler.removeMessages(1);
                }
                //1000: //EditText输入变化延迟时间1s
                mHandler.sendEmptyMessageDelayed(1, 2000);
            }
        });

        //设置默认头像
        Glide.with(this).load(R.drawable.img_icon).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(imageView);
    }

    private static class MyHandler extends Handler {
        WeakReference<LoginActivity> mActivityReference;
        MyHandler(LoginActivity activity) {
            mActivityReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            LoginActivity activity = mActivityReference.get();
            if (activity != null) {
                if(msg.what==1){
                    String uName= activity.editText_name.getText().toString();
                    activity.httpGetIcon(uName);
                }
            }
        }
    }


    //获取用户头像
    private void httpGetIcon(String s) {
        HashMap<String, String> map = new HashMap<>();
        map.put("username", s);
        Ihttp.getInstance().post(MyHttpURL.mainUrl + "user/findUser", map, User.class, new CallBackObject<User>() {
            @Override
            public void success(User ojb) {
                User user = ojb;
                if (user != null) {
                    //加载用户头像
                    Glide.with(LoginActivity.this).load(user.getUrl())
                            .placeholder(R.drawable.dra_imgloading)//设置加载中图片
                            .error(R.drawable.img_icon)
                            .fallback(R.drawable.img_icon)
                            .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                            .into(imageView);
                }
            }


            @Override
            public void fail(String s) {

            }
        });
    }

    //按钮 执行登录操作
    public void LoginClick(View view) {
        if (Sys.isClick()) {
            username = editText_name.getText().toString();
            password = editText_psd.getText().toString();
            if (username.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (username.equals("admin")&&password.equals("123")){
                startActivity(new Intent(this,MainActivity.class));
                return;
            }

            dialogLoading = Ohuang.dialogLoadingshow(this, "登录中");
            HttpLogin();//执行登录

        }
    }

    //登录
    private void HttpLogin() {
        HashMap<String, String> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        Ihttp.getInstance().post(MyHttpURL.mainUrl + "user/login", map, new CallBackString() {
            @Override
            public void success(String ojb) {
                String code = ojb;
                if ("success".equals(code)) {
                    myHandler.sendEmptyMessage(SI_SUCCESS);
                } else if ("error".equals(code)) {
                    myHandler.sendEmptyMessage(SI_FAIL);
                } else {
                    myHandler.sendEmptyMessage(SI_OTHER);
                }
            }
            @Override
            public void fail(String s) {
                myHandler.sendEmptyMessage(SI_ERROR);
            }
        });


    }

    //按钮   打开注册页面
    public void StartRegisterClick(View view) {
        if (Sys.isClick()) {
            startActivity(new Intent(this, RegisterActivity.class));
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case SI_SUCCESS:
                    dialogLoading.dismiss();
                    try {
                        Ohuang.writefile(LoginActivity.this, "username.txt", username);//写入文件
                        Ohuang.writefile(LoginActivity.this, "password.txt", password);//写入文件
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    HttpGetUser();//获取用户信息

                    break;
                case SI_FAIL:
                    dialogLoading.dismiss();
                    Ohuang.dialogshow(LoginActivity.this, "登录失败", "用户名或密码错误");
                    break;
                case SI_ERROR:
                    dialogLoading.dismiss();
                    Ohuang.dialogshow(LoginActivity.this, "登录失败", "网络连接错误");
                    break;
                case SI_OTHER:
                    dialogLoading.dismiss();
                    Ohuang.dialogshow(LoginActivity.this, "登录失败", "返回值错误");
                    break;

            }
        }
    };

    private void HttpGetUser() {
        HashMap<String, String> map = new HashMap<>();
        map.put("username", username);
        Ihttp.getInstance().post(MyHttpURL.mainUrl + "user/findUser", map, User.class, new CallBackObject<User>() {
            @Override
            public void success(User ojb) {
                User user = ojb;
                if (user != null) {
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent.putExtra("User", user);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, "获取用户信息失败", Toast.LENGTH_SHORT).show();
                }
            }



            @Override
            public void fail(String s) {
                Toast.makeText(LoginActivity.this, "获取用户信息失败", Toast.LENGTH_SHORT).show();
            }
        });

    }


}
